#!usr/bin/python
# -*- coding:utf-8 -*-
# Copyright 2020 labsight
import time
import smtplib
from email.mime.text import MIMEText

TIMESTAMP = {
    '0': 'unie_email@126.com',
    '1': 'unie_email@126.com',
    '2': 'unie_email@126.com',
    '3': 'unie_email@126.com',
    '4': 'unie_email@163.com',
    '5': 'unie_email@163.com',
    '6': 'unie_email@163.com',
    '7': 'unie_email@126.com',
    '8': 'unie_email@163.com',
    '9': 'unie_email@163.com',
}

EMAIL = {
    'unie_email@126.com': {
        'addr': 'unie_email@126.com',
        'pw': 'Yht993613',
        'pwd': 'VIDXHVNIPABMFTFW',
        'host': 'smtp.126.com',
        'port': 465},
    'unie_email@163.com': {
        'addr': 'unie_email@163.com',
        'pw': 'Yht993613',
        'pwd': 'TOPWNIANYVZGSUPP',
        'host': 'smtp.163.com',
        'port': 465},
    'unie_email@yeah.net': {
        'addr': 'unie_email@yeah.net',
        'pw': 'Yht993613',
        'pwd': 'BXTBOYMTWPXFCLNC',
        'host': 'smtp.yeah.net',
        'port': 465},
}

class Email:
    def __init__(self, log):
        self.log = log

    def sendemail(self, subject, body):
        try:
            timestamp = time.time()
            index = TIMESTAMP.get(str(timestamp)[len(str(timestamp)) - 1])
            sender = EMAIL.get(index).get('addr')
            pwd = EMAIL.get(index).get('pwd')
            host = EMAIL.get(index).get('host')  # 设置发件服务器地址
            port = EMAIL.get(index).get('port')  # 设置发件服务器端口号。注意，这里有SSL和非SSL两种形式，现在一般是SSL方式
            receiver = 'unie_monitor@163.com'
            body = body
            msg = MIMEText(body, 'html')  # 设置正文为符合邮件格式的HTML内容
            msg['subject'] = subject  # 设置邮件标题
            msg['from'] = sender  # 设置发送人
            msg['to'] = receiver  # 设置接收人
            self.log.info('邮件构建成功:主题：%s' % (subject))
        except Exception as e:
            self.log.error('邮件构建失败')
        try:
            s = smtplib.SMTP_SSL(host, port)
            s.login(sender, pwd)  # 登陆邮箱
            s.sendmail(sender, receiver, msg.as_string())  # 发送邮件！
            self.log.info('邮件发送成功:发件人：%s，收件人：%s' % (sender, receiver))
        except smtplib.SMTPException:
            self.log.error(smtplib.SMTPException)
            self.log.error('邮件发送失败:发件人：%s，收件人：%s' % (sender, receiver))
